# libraries ---------------------------------------------------------------

# load functions ----------------------------------------------------------

# Step 1)
source("./R/utils.R")
source("./R/descriptives.R")
source("./R/regression.R")
source("./R/regression_discontinuity.R")
source("./R/rdd_and_placebo_on_all_data.R")
source("./R/robustness_winner_is_senior_or_junior_coalition_partner.R")
source("./R/robustness_balance.R")
source("./R/RDD_electoral_losers_rdd_with_abstainers.R")

# generate data -----------------------------------------------------------

data <- prepare_data(
  filenames = list(
    iceland = "./original_data/iceland_dataset.dta",
    norway = "./original_data/cses1.rdata",
    netherlands = list(
      main = "./original_data/ESS - including NL2012.csv",
      additional = "./original_data/ESS-Data-Wizard-subset-2023-02-07.csv"
    )
  )
)

# analysis sequence -------------------------------------------------------

# Step 2)
# descriptive statistics
descriptives(data = data)

# Step 3)
# regression and coefficient plot
regression(data = data)

# Step 4)
# RDD
regression_discontinuity(
  data = data, var_cutoffs = var_cutoffs, est_rdd_power = est_rdd_power
)

# Step 5)
# RDD + placebo analysis on all data
rdd_and_placebo_on_all_data(
  data = data,
  rdd_model = rdd_model,
  rdd_plot = rdd_plot,
  permutation_analysis = permutation_analysis,
  est_rdd_power = est_rdd_power,
  winners_power = winners_power,
  permutation_plot = permutation_plot
)

# Step 6)
# robustness balance
robustness_balance(data = data, balance_table = balance_table)

# Step 7)
# robustness test: abstainers included in losers category -----------------

data <- prepare_data(
  filenames = list(
    iceland = "./original_data/iceland_dataset.dta",
    norway = "./original_data/cses1.rdata",
    netherlands = list(
      main = "./original_data/ESS - including NL2012.csv",
      additional = "./original_data/ESS-Data-Wizard-subset-2023-02-07.csv"
    )
  ),
  abstainers = TRUE
)

RDD_electoral_losers_rdd_with_abstainers(data = data, rdd_model = rdd_model)
